package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: Li zi long
 * @date: 2021/10/19 16:50
 * @description:
 */
@Component
public class AccessFilter extends ZuulFilter {

    //过滤器的类型:pre(前置),route(路由),(后置)post,error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;//FilterConstants.PRE_TYPE = "pre"
    }

    //顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //针对当前请求进行判断,是否要执行下面的过滤代码
    @Override
    public boolean shouldFilter() {
        //调用后台商品服务需要检查权限
        //调用用户和订单可以直接访问

        //获得RequestContext对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获取访问的后台服务id
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);//"serviceId"
        //判断服务id是否是"item-service"
        return "item-service".equals(serviceId);
    }

    //过滤代码,检查用户权限
    @Override
    public Object run() throws ZuulException {
        //获取请求上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象获取request对象
        HttpServletRequest request = ctx.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应
        //"".equals(token) || token == null || token.length() != 0
        //isEmpty() = "  " 为 false  isBlank() = "  " 为true
        if (StringUtils.isBlank(token)) {
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接返回响应
            //JsonResult -- {code: 400, msg: 未登录, data: null}
            String json = JsonResult.err()
                    .code(400)
                    .msg("Not Login, 未登录")
                    .toString();
            ctx.addZuulResponseHeader("Context-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(json);
        }
        return null;
    }
}
